<template>
  <el-row>
    <el-input
        v-model="topic"
        placeholder="请输入topic查询"
        @blur="topicSearch"
        style="width: 550px"/>
    <el-select
        v-model="timeType"
        clearable
        placeholder="请选择时间区间"
        @change="timeListChange"
        class="margin-node"
        style="width: 150px"
    >
      <el-option
          v-for="item in timeLists"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
    <el-date-picker
        v-if="timeType === 'custom'"
        v-model="timeRange"
        type="datetimerange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        @change="timeRangeChange"
        format="YYYY-MM-DD HH:mm:ss"
        date-format="YYYY/MM/DD ddd"
        time-format="A hh:mm:ss"
        class="margin-node"
        style="width: 350px"
    />
    <el-button
        icon="el-icon-search"
        type="primary"
        @click="search"
        class="margin-node">
      搜 索
    </el-button>
    <el-button
        icon="el-icon-delete"
        @click="clearSearch"
        class="margin-node">
      清 空
    </el-button>
  </el-row>
  <el-row>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model="form"
               ref="crud"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
    </avue-crud>
  </el-row>
</template>

<script>
import {getLogMessage} from "@/api/iot/device/sequence";
import {validatenull} from "@/utils/validate";
import func from "@/utils/func";

export default {
  name: 'deviceLog',
  props: {
    productKey: String,
    deviceId: String,
    deviceName: String,
    simplifyMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      loading: false,
      selectionList: [],
      topic: '',
      timeType: '',
      timeRange: [],
      option: {
        height: 'auto',
        calcHeight: 172,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        header: false,
        border: true,
        index: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        menu: false,
        dialogWidth: 500,
        labelWidth: 120,
        searchLabelWidth: 100,
        column: [
          {
            label: "更新时间",
            prop: "time",
            width: 200,
          },
          {
            label: 'topic',
            prop: 'topic',
          },
          {
            label: '消息内容',
            prop: 'message',
          },
        ]
      },
      data: [],
      timeLists: [{
        label: '最近一小时',
        value: '1h',
      }, {
        label: '最近一天',
        value: '1d',
      }, {
        label: '最近一周',
        value: '1w',
      }, {
        label: '最近一个月',
        value: '1m',
      }, {
        label: '自定义区间',
        value: 'custom',
      }],
    };
  },
  watch: {
    // deviceId不是路由传参获取，在上级路由调用接口查询获取
    // 有时间差导致子组件创建时取不到值，监听到值后进行数据获取
    deviceId() {
      if (!validatenull(this.deviceId)) {
        this.onLoad(this.page, this.query);
      }
    }
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    // 在这里可以安全地进行DOM操作
    this.$nextTick(() => {
      // 代码在这里确保整个视图已经更新完毕
      if (this.simplifyMode) {
        this.$refs.crud.option.size = "small";
        this.$refs.crud.option.column.filter(item => {
          if (item.prop === 'time') {
            item.width = 150;
          }
          if (item.prop === 'productKey' || item.prop === 'deviceName') {
            item.hide = true;
          }
        });
      }
    });
  },
  methods: {
    search() {
      this.query = {
        ...this.query,
        topic: this.topic,
        timeList: this.timeRange
      };
      this.onLoad(this.page, this.query);
    },
    clearSearch() {
      this.topic = '';
      this.timeType = '';
      this.timeRange = [];
      this.query = {};
      this.onLoad(this.page, this.query);
    },
    topicSearch() {
      this.query = {
        ...this.query,
        topic: this.topic
      };
      this.onLoad(this.page, this.query);
    },
    calculateTimeRange() {
      const today = new Date();
      const tomorrow = new Date();
      today.setHours(0, 0, 0, 0); // 当天0点
      tomorrow.setDate(tomorrow.getDate() + 1);
      tomorrow.setHours(0, 0, 0, 0); // 第二天0点
      return [today, tomorrow];
    },
    timeListChange(value) {
      this.timeType = value;
      let timeList = [];

      if (!validatenull(value)) {
        // 获取当前时间
        const now = new Date();
        if (value === '1h') {
          // 最近一小时
          const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
          timeList = [oneHourAgo, now];
        } else if (value === '1d') {
          // 最近一天
          const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
          timeList = [oneDayAgo, now];
        } else if (value === '1w') {
          // 最近一周
          const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          timeList = [oneWeekAgo, now];
        } else if (value === '1m') {
          // 最近一个月
          const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
          timeList = [oneMonthAgo, now];
        } else if (value === 'custom') {
          this.timeRange = this.calculateTimeRange();
          // 自定义区间
          timeList = [this.timeRange[0], this.timeRange[1]];
        } else {
          console.log('Unexpected value:', value);
        }
        timeList = [
          func.toLocalISOString(timeList[0]),
          func.toLocalISOString(timeList[1])
        ];
        this.timeRange = timeList;
      }

      this.query = {
        ...this.query,
        timeList
      };
      this.onLoad(this.page, this.query);
    },
    timeRangeChange(value) {
      this.timeRange = value;
      let timeList = [];
      if (!validatenull(value)) {
        timeList = [
          func.toLocalISOString(value[0]),
          func.toLocalISOString(value[1])
        ];
      }
      this.query = {
        ...this.query,
        timeList
      };
      this.onLoad(this.page, this.query);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      // deviceId不是路由传参获取，在上级路由调用接口查询获取
      // 有时间差导致子组件创建时取不到值，所以需要进行判断
      if (validatenull(this.deviceId)) {
        return;
      }
      if (validatenull(page)) {
        page = this.page;
      }
      this.loading = true;
      let values = {
        ...params,
        deviceId: this.deviceId,
      };
      getLogMessage(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map(record => {
          return {
            ...record, // 复制原有的record中的所有字段
            time: func.formatDateTime(record.time) // 更新time字段
          };
        });
        this.loading = false;
      });
    }
  }
};
</script>

<style>
.margin-node {
  margin-left: 12px;
}
</style>
